﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Media;

namespace Windows.UI.Xaml
{
    public static class VisualTreeExtensions
    {
        public static T GetChildObject<T>(this DependencyObject obj, string name) where T : DependencyObject
        {
            for (int i = 0; i < VisualTreeHelper.GetChildrenCount(obj); i++)
            {
                DependencyObject c = VisualTreeHelper.GetChild(obj, i);
                if (c.GetType().Equals(typeof(T)) && (String.IsNullOrEmpty(name) || ((FrameworkElement)c).Name == name))
                {
                    return (T)c;
                }
                DependencyObject gc = GetChildObject<T>(c, name);
                if (gc != null)
                    return (T)gc;
            }
            return null;
        }
        public static IEnumerable<T> GetChildObjects<T>(this DependencyObject obj) where T : DependencyObject
        {
            for (int i = 0; i < VisualTreeHelper.GetChildrenCount(obj); i++)
            {
                DependencyObject c = VisualTreeHelper.GetChild(obj, i);
                if (c.GetType().Equals(typeof(T)))
                    yield return (T)c;

                var gc = GetChildObjects<T>(c);
                if (gc != null)
                    foreach(var ri in gc)
                        yield return (T)ri;
            }
            yield break;
        }
    }
}
